<script setup lang="ts">
import {onMounted, PropType, ref} from 'vue';
import {Empty, InputSearch, Tree} from 'ant-design-vue';
import {findDeptListTree} from '#/api/system/dept';

const emits = defineEmits(['select']);

const selectDeptId = defineModel('selectDeptId', {
  required: true,
  type: Array as PropType<number[]>,
})

const searchValue = defineModel('searchValue', {
  type: String as PropType<string>,
  default: '',
})

const deptTreeList = ref([]);

const getDeptListTree = (params) => {
  findDeptListTree(params).then(res => {
    if (res) {
      deptTreeList.value = res;
    } else {
      deptTreeList.value = [];
    }
  });
}

const handleDeptSearch = () => {
  getDeptListTree({name: searchValue.value});
}

onMounted(() => {
  getDeptListTree();
});
</script>

<template>
  <div class="dept-tree bg-card rounded-md mr-3 p-2">
    <InputSearch
        v-model:value="searchValue"
        @search="handleDeptSearch"
        @change="handleDeptSearch"
        allowClear
        placeholder="搜索"/>

    <div class="h-[calc(100%-3rem)] overflow-y-auto px-2">
      <Tree
          v-model:selected-keys="selectDeptId"
          :tree-data="deptTreeList"
          :fieldNames="{key: 'id', title:'name', children: 'children'}"
          @select="() => emits('select')"
          draggable
          block-node
          :virtual="false"
          :default-expanded-keys="[1]"
          v-if="deptTreeList?.length > 0"
          class="pt-1">
      </Tree>

      <Empty v-else class="pt-5"/>
    </div>
  </div>
</template>

<style scoped lang="scss">
.dept-tree {
  height: calc(100%);

  :deep(.ant-tree .ant-tree-node-content-wrapper) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  :deep(.ant-input-group-addon) {
    border: none;
  }

  :deep(.ant-tree-list) {
    border-top-width: 1px;
  }

  :deep(.ant-tree-list-holder) {
    margin-top: 0.3rem;
  }
}
</style>